package com.longqin.business.config;

import java.lang.reflect.Method;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;

@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
	
	
    @Bean(name="lockRedisTemplate")
    public RedisTemplate<String, Object> lockRedisTemplate(RedisConnectionFactory factory) {
    	RedisTemplate<String, Object> template = new RedisTemplate<>();
    	StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
    	template.setKeySerializer(stringRedisSerializer);
    	template.setValueSerializer(stringRedisSerializer);
    	template.setHashKeySerializer(stringRedisSerializer);
    	template.setHashValueSerializer(stringRedisSerializer);
    	//连接Redis
    	template.setConnectionFactory(factory);
    	template.afterPropertiesSet();
    	return template;
    }
    
	@Bean(name = "redisTemplate")
	public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
		RedisTemplate<String, String> template = new RedisTemplate<>();
		RedisSerializer<String> redisSerializer = new StringRedisSerializer();
		Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = getJackson2JsonRedisSerializer();
		template.setConnectionFactory(factory);
		// key序列化方式
		template.setKeySerializer(redisSerializer);
		// value序列化
		template.setValueSerializer(jackson2JsonRedisSerializer);
		// value hashmap序列化
		template.setHashValueSerializer(jackson2JsonRedisSerializer);
		return template;
	}

	
	/**配合cache注解使用
	 * @param factory
	 * @return
	 */
	@Bean
	public CacheManager cacheManager(RedisConnectionFactory factory) {
		// 对每个缓存空间应用不同的配置
        Map<String, RedisCacheConfiguration> configMap = new HashMap<>();
        configMap.put("access", getRedisCacheConfiguration().entryTtl(Duration.ofSeconds(7180L)));//access_token这个缓存空间7180秒
		return RedisCacheManager.builder(factory)
			   .cacheDefaults(getRedisCacheConfiguration())//默认缓存
			   .withInitialCacheConfigurations(configMap)//缓存策略
			   .build();
	}
	
    /**RedisCacheConfiguration默认状态
     * @return
     */
    private  RedisCacheConfiguration getRedisCacheConfiguration() {
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
    	RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
        .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
        .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(getJackson2JsonRedisSerializer()))
        .disableCachingNullValues();
    	return config;
    }
    
    /**Jackson2JsonRedisSerializer默认配置
     * @return
     */
    private Jackson2JsonRedisSerializer<Object> getJackson2JsonRedisSerializer(){
    	Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
        //解决查询缓存转换异常的问题
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
		return jackson2JsonRedisSerializer;
    }

    
	@Bean
	public KeyGenerator keyGenerator() {
		return new KeyGenerator() {
			@Override
			public Object generate(Object target, Method method, Object... params) {
				StringBuilder sb = new StringBuilder();
				sb.append(target.getClass().getName());
				sb.append(method.getName());
				for (Object obj : params) {
					sb.append(obj.toString());
				} 
				return sb.toString();
			}
		};
	}
}
